import { Injectable } from '@nestjs/common';
import OpenAI from 'openai';
import { Observable } from 'rxjs';

@Injectable()
export class OpenaiService {
  async question(apiKey: string | undefined, query: string) {
    try {
      const openai = new OpenAI({
        apiKey: apiKey,
        baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
      });

      const completion = await openai.chat.completions.create({
        model: 'qwen-plus', // 此处以qwen-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
        messages: [
          { role: 'system', content: 'You are a helpful assistant.' },
          { role: 'user', content: query },
        ],
        stream: true,
      });

      return new Observable((observer) => {
        (async () => {
          for await (const chunk of completion) {
            const node = chunk.choices[0] || {};
            const content = Buffer.from(
              node.delta?.content || '',
              'utf8',
            ).toString('utf8');
            observer.next({
              content: content,
              finish_reason: node.finish_reason,
            });
          }
          observer.complete();
        })();
      });
    } catch (error) {
      console.log(`错误信息：${error}`);
      console.log(
        '请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code',
      );
      return Promise.reject(error);
    }
  }
}
